package com.tidc.seaserverservice.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tidc.seaservermapper.dao.*;
import com.tidc.seaservermodel.config.RabbitConfig;
import com.tidc.seaservermodel.entity.*;
import com.tidc.seaservermodel.exception.TidcBadParent;
import com.tidc.seaservermodel.util.SpringUtil;
import com.tidc.seaserverservice.service.SecondaryShopService;
import com.tidc.seaserverservice.util.RabbitUtil;
import com.tidc.seaserverservice.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.annotation.Transient;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/9/27 13:45
 * @description：
 * @modified By：
 * @version:
 */
@Service
@Slf4j
public class SecondaryShopServiceImpl implements SecondaryShopService {
    @Resource
    private ShopDao shopDao;
    @Resource
    private UserUtil userUtil;
    @Resource
    private OrderFormDao orderFormDao;
    @Resource
    private UserDao userDao;
    @Resource
    private UserPackageDao userPackageDao;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RabbitUtil rabbitUtil;
    @Resource
    private RabbitMessageLogDao rabbitMessageLogDao;
    @Override
    public Fres<Map<Object, Object>> getShopList(int pageSize, int pageNum, Authentication authentication) throws TidcBadParent {
        User user = userUtil.getUser(authentication);
        int count = shopDao.getSecondaryShopListCount(user.getSuperiorUserId());
        Map<Object, Object> map = SpringUtil.pagingPrepare(pageSize, pageNum, count);
        List<Shop> secondaryList = shopDao.getSecondaryList((pageNum - 1) * pageSize, pageSize, user.getSuperiorUserId());
        map.put("list",secondaryList);
        return Fres.Success(map,"成功");
    }
//    TODO 锁行知识盲区 锁用户表里的金额 以及 库存表里的数量 后续增加
    @Transactional(rollbackFor = {SQLException.class})
    @Override
    public Fres<String> buyShop(OrderForm orderForm, Authentication authentication) throws SQLException, JsonProcessingException {
        Fres<String> fres = null;
        boolean flag = true;
        User user = userUtil.getUser(authentication);
        Shop shop = shopDao.queryById(orderForm.getShopId(), user.getSuperiorUserId());
        if (orderForm.getAmount()<=0){
            fres = Fres.badRequestParent("数量不能为0","数量不能为0");
            flag = false;
        }
        if(user.getMoney()<shop.getMoney()*orderForm.getAmount()){
            fres  = Fres.badRequestParent("账号资金不足", "账号资金不足");
            flag = false;
        }
        if(shop.getAmount()<orderForm.getAmount()){
            fres  = Fres.badRequestParent("奖励可兑换次数不足", "奖励可兑换次数不足");
            flag = false;
        }
        if(user.getLevelValue()<shop.getPrepositionLevel()){
            fres  = Fres.badRequestParent("没达到要求等级", "没达到要求等级");
            flag = false;
        }
        if(flag){
            //插入订单
            orderForm.setShopName(shop.getName()).setShopIntroduce(shop.getIntroduce()).setUserId(user.getId()).setMoney(shop.getMoney()*orderForm.getAmount());
            orderFormDao.insert(orderForm);
            //插入仓库
            UserPackage countAndId = userPackageDao.getCountAndId(shop.getId(), shop.getUpdateTime());
            if(countAndId == null){
                //插入
                countAndId = new UserPackage();
                countAndId.setShopId(shop.getId()).setAmount(orderForm.getAmount()).setShopIntroduce(shop.getIntroduce())
                        .setShopUpdateTime(shop.getUpdateTime()).setShopName(shop.getName()).setUserId(user.getId()).setTimeout(shop.getTimeout());
                userPackageDao.insert(countAndId);
            }else{
                //增加库存
                countAndId.setAmount(countAndId.getAmount()+orderForm.getAmount());
                userPackageDao.update(countAndId);
            }
            //减少库存
            shop.setAmount(shop.getAmount()-orderForm.getAmount());
            shopDao.updateAmount(shop.getAmount(),shop.getId());
            //扣钱
            userDao.deductMoney(shop.getMoney()*orderForm.getAmount(),user.getId());
            fres = Fres.Success();
            Email email =Email.secondaryBuyShopEmail(user.getUsername(),orderForm.getAmount(),shop.getName(),user.getSuperiorUserId());
            RabbitMessageLog rabbitMessageLog = RabbitMessageLog.sendEmail(objectMapper.writeValueAsString(email));
            rabbitUtil.sendMQ(rabbitMessageLog);
        }
        return fres;
    }
}
